from flask import jsonify, session


# 验证登陆状态
class AuthMiddleware:

    def __init__(self, app):
        self.app = app.wsgi_app
        self.flask_app = app

    def __call__(self, environ, start_response):
        path = environ['PATH_INFO']

        if path in [
                '/api/user/login', '/api/user/register', '/api/user/logout',
                '/api/user/retrieve_password'
        ]:
            return self.app(environ, start_response)

        with self.flask_app.request_context(environ):
            print(session.get('islogin'))
            if not session.get('islogin'):
                response = jsonify({
                    'success': 0,
                    'errors': {
                        'islogin': '登录状态失效'
                    },
                    'msg': '登录状态失效',
                    'data': {}
                })
                response.status_code = 401
                return response(environ, start_response)
        return self.app(environ, start_response)
